package org.example.controller;

import org.example.domain.Student;
import org.example.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(value = "/queryStudent")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");//设置response 编码
        Connection connection= JDBCUtil.getConnection();
        String sql="select id,name,sex,mobile_phone,address,class_name,student_id,score from table1";

        PreparedStatement stmt=null;
        ResultSet rs=null;
        try {
            stmt=connection.prepareStatement(sql);
            rs=stmt.executeQuery();
            List<Student> studentList = new ArrayList<Student>();
            while (rs.next()) {
                Student st = new Student();
                st.setId(rs.getLong("id"));
                st.setName(rs.getString("name"));
                st.setSex(rs.getString("sex"));
                st.setMobilePhone(rs.getString("mobile_phone"));
                st.setAddress(rs.getString("address"));
                st.setClassName(rs.getString("class_name"));
                st.setStudentID(rs.getString("student_id"));
                st.setScore(rs.getString("score"));
                studentList.add(st);
            }
            req.getSession().setAttribute("studentList", studentList);
            resp.sendRedirect("data1.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.closeAll(rs,stmt,connection);
        }
    }
}
